package com.xw.tools.view;

import com.xw.tools.util.Base64Util;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;

public class Base64ToFileWin extends AbstractWin {

    public void start() {
        Stage primaryStage = new Stage();
        primaryStage.setTitle("Base64转文件");
        Scene scene = new Scene(new VBox(), 800, 495);
        initView(scene, primaryStage);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void initView(Scene scene, Stage primaryStage) {
        TextArea inputTextArea = new TextArea();
        inputTextArea.setWrapText(true);
        inputTextArea.setFont(Font.font(16));
        TextField textField = new TextField();
        Button fileBtn = new Button("选择保存路径");
        fileBtn.setOnAction((ActionEvent t) -> {
            FileChooser fileChooser = new FileChooser();
            File file = fileChooser.showSaveDialog(primaryStage);
            if (file != null) {
                textField.setText(file.getAbsolutePath());
            }
        });

        Button button = new Button("Decode");
        button.setOnAction((ActionEvent t) -> {
            String text = inputTextArea.getText();
            if (text == null || text.isEmpty()) {
                return;
            }
            String filePath = textField.getText();
            if (new File(filePath).exists()) {
                return;
            }
            boolean b = Base64Util.decodeToFile(text, filePath);
            if (b) {
                Alert info = new Alert(Alert.AlertType.INFORMATION,"文件转换成功!");
                info.setTitle("温馨提示");
                info.setHeaderText("");
                info.show();
            }
        });

        VBox box = (VBox) scene.getRoot();
        box.getChildren().add(inputTextArea);
        HBox hBox = new HBox();
        hBox.getChildren().add(textField);
        hBox.getChildren().add(fileBtn);
        HBox.setHgrow(textField, Priority.ALWAYS);
        HBox.setHgrow(fileBtn, Priority.ALWAYS);

        box.getChildren().add(hBox);
        VBox.setMargin(fileBtn, new Insets(10, 0, 10, 0));
        VBox.setVgrow(inputTextArea, Priority.ALWAYS);
        box.getChildren().add(button);
    }

    @Override
    public void show() {
        start();
    }
}
